package com.hengpeng.itfints.tools;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

public class HttpsUtils
{
	private final static Log logger = LogFactory.getLog(HttpsUtils.class);

	public static String post(String url, Map<String, String> paramters, String encoding) throws Exception
	{
		String result = "";
		HttpClient httpClient = null;
		try
		{
			X509TrustManager tm = new X509TrustManager()
			{
				public void checkClientTrusted(X509Certificate[] xcs, String string)
				{
				}

				public void checkServerTrusted(X509Certificate[] xcs, String string)
				{
				}

				public X509Certificate[] getAcceptedIssuers()
				{
					return null;
				}
			};

			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory socketFactory = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
			Scheme sch = new Scheme("https", 443, socketFactory);
			SchemeRegistry schemeRegistry = new SchemeRegistry();
			schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			schemeRegistry.register(sch);
			HttpParams params = new BasicHttpParams();
			params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
			params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
			params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
			httpClient = new DefaultHttpClient(cm, params);
			// 获得HttpGet对象
			HttpPost post = new HttpPost(url);
			if (paramters != null && paramters.size() > 0)
			{
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> entry : paramters.entrySet())
				{
					list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				post.setEntity(new UrlEncodedFormEntity(list, encoding));
			}
			// 发送请求
			HttpResponse response = httpClient.execute(post);
			// 输出返回值
			InputStream is = response.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
			String line = "";
			while ((line = br.readLine()) != null)
			{
				result += line;
			}
		}
		catch (Exception ex)
		{
			logger.error("https请求错误", ex);
		}
		finally
		{
			httpClient.getConnectionManager().shutdown();
		}
		return result;
	}

	public static void main(String[] args) throws Exception
	{
		Map<String, String> param = new HashMap<String, String>();
		param.put("client_id", "1127915928");
		param.put("client_secret", "9cdffe103cacd691b3aec8cde9ea99d8");
		param.put("grant_type", "authorization_code");
		param.put("redirect_uri", "http://www.happycp.com");
		param.put("code", "c05f55b295f4f8f0777f04df20403efc");
//		System.out.println(post("https://api.weibo.com/oauth2/access_token", param, "gbk"));
	}
}
